var Koa =require('koa');
var router =require('koa-router')(); 
var views=require('koa-views')
var bodyParser=require('koa-bodyparser') //使用bodyparser1.安装引入
var static =require('koa-static')
var render=require('koa-art-template')
var path=require('path')
var DB=require('./module/db')
var app= new Koa();  
app.use(bodyParser())
render(app,{
    root:path.join(__dirname,'views'),//视图位置
    extname:'.html', //后缀名
    debug:process.env.NODE_ENV!=='production'
})

router.get('/', async (ctx)=>{
   let reslut=await DB.find('user',{});
   console.log(reslut)
    await ctx.render('index',{
        list:reslut
    })
}) 
router.get('/add',async (ctx,next)=>{ 
    await ctx.render('add') 
})
router.post('/doAdd',async (ctx,next)=>{
   let addData= ctx.request.body;
    let data=await DB.insert('user',addData)  ;
    
            ctx.redirect('/')
   
})
router.get('/edit',async (ctx,next)=>{
    let id=ctx.query.id;
    let data=await DB.find('user',{_id:DB.getObjectId(id)})
    console.log(40,data)
    await ctx.render('edit',{list:data[0]}) 
    // let data=await DB.update('user',{'username':'lisi'},{'username':'李四'})
    // console.log(data.reslut)
})
router.post('/doEdit',async (ctx,next)=>{
    
   let id= ctx.request.body.id;
   let username= ctx.request.body.username;
   let age= ctx.request.body.age;
   let data=await DB.update('user',{'_id':DB.getObjectId(id)},{username,age})  ;
   console.log(52,data)
   console.log(53,data.reslut)
   ctx.redirect('/')
    
})
router.get('/delete',async (ctx,next)=>{
    
    let id=ctx.query.id;
    let data=await DB.remove('user',{_id:DB.getObjectId(id)});
    ctx.redirect('/')
})

app.use(router.routes())
app.use(router.allowedMethods()) 

app.listen(8081)